//
//  PicturePickerController.swift
//  01-照片选择
//
//  Created by male on 15/10/26.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

/// 可重用 cell
private let PicturePickerCellId = "PicturePickerCellId"
/// 最大选择照片数量
private let PicturePickerMaxCount = 8

/// 照片选择控制器
class PicturePickerController: UICollectionViewController {
    //测试闭包
//    var addB:((cell:UICollectionViewCell)->())? = { (cell)->() in
//        print("add")
//        print(cell)
//    }
//    var removeB:((cell:UICollectionViewCell)->())? = { (cell)->() in
//        print("remove")
//        print(cell)
//    }
    
    /// 配图数组
    lazy var pictures = [UIImage]()
    /// 当前用户选中的照片索引
    private var selectedIndex = 0
    
    // MARK: - 构造函数
    init() {
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 在 CollectionViewController 中 collectionView != view
    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        // 注册可重用 Cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)
    }
    
    // MARK: - 照片选择器布局
    private class PicturePickerLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            // iOS 9.0 之后，尤其是 iPad 支持分屏，不建议过分依赖 UIScreen 作为布局参照！
            // iPhone 6s- 2/iPhone 6s+ 3
            let count: CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
        }
    }
}

extension PicturePickerController {
        override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return pictures.count + 1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell
        // 设置代理
        cell.pictureDelegate = self
        //测试闭包
//        cell.addBibao = addB
//        cell.removeBibao = removeB
        cell.image = indexPath.row < pictures.count ? pictures[indexPath.row]:nil
        return cell
    }
}

// MARK: - PicturePickerCellDelegate
extension PicturePickerController: PicturePickerCellDelegate {
    
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        let picker = UIImagePickerController()
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            return
        }
        picker.delegate = self
       // picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
        let index = collectionView!.indexPathForCell(cell)!
        if index.item >= pictures.count {
            return
        }
        pictures.removeAtIndex(index.item)
        collectionView?.deleteItemsAtIndexPaths([index])
        //collectionView?.reloadData()
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerController:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleImage(300)
        pictures.append(scaleImage)
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}
/// PicturePickerCellDelegate 代理
/// 如果协议中包含 optional 的函数，协议需要使用 @objc 修饰
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
    
    /// 添加照片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    /// 删除照片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}

/// 照片选择 Cell - private修饰类，内部的一切方法和属性，都是私有的
private class PicturePickerCell: UICollectionViewCell {
    //测试闭包
//    var addBibao:((cell:UICollectionViewCell)->())?
//    var removeBibao:((cell:UICollectionViewCell)->())?
    /// 照片选择代理
    weak var pictureDelegate: PicturePickerCellDelegate?
    
    //图片属性
    var image:UIImage?{
        didSet{
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            if image != nil{
                removeButton.hidden = false
            }
        }
    }
    // MARK: - 监听方法
    @objc func addPicture() {
        pictureDelegate?.picturePickerCellDidAdd?(self)
        //addBibao?(cell: self)
        
    }
    
    @objc func removePicture() {
        pictureDelegate?.picturePickerCellDidRemove?(self)
         //removeBibao?(cell: self)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置控件
    private func setupUI() {
        // 1. 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        // 2. 设置布局
        addButton.frame = bounds
        removeButton.hidden = true
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        // 3. 监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        // 4. 设置填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    // MARK: - 懒加载控件
    /// 添加按钮
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    /// 删除按钮
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}